<template>
  <div class="home-container">
    <!-- 用户信息和设置 -->
    <div class="user-settings">
      <van-popover
        v-model:show="showUserMenu"
        placement="bottom-end"
        theme="dark"
        trigger="click"
      >
        <template #reference>
          <div class="user-avatar">
            <van-icon name="manager" size="20" />
          </div>
        </template>
        <div class="menu-item" @click="goToResetPassword">
          <van-icon name="lock" />
          <span>修改密码</span>
        </div>
        <div class="menu-item" @click="logout">
          <van-icon name="cross" />
          <span>退出登录</span>
        </div>
      </van-popover>
    </div>
    
    <!-- 总览模块 -->
    <div class="overview-card" @click="showIncomeExpenseDetail = true">
      <div class="overview-title">账户总览</div>
      <div class="overview-row">
        <div class="overview-item income">
          <span class="label">当前总额</span>
          <span class="amount">￥{{ moneyUtils.formatMoney(overview.amount) }}</span>
        </div>
        <div class="overview-item income yesterday-item">
          <span class="label">
            昨日总额
            <van-button size="mini" class="edit-btn small-edit-btn" style="margin-left: 4px;" @click.stop="showEditYesterday = true">修改</van-button>
          </span>
          <span class="amount">￥{{ moneyUtils.formatMoney(overview.yesterdayAmount) }}</span>
        </div>
        <div class="overview-item" :class="growthAmount >= 0 ? 'income' : 'expense'">
          <span class="label">增长额</span>
          <span class="amount">￥{{ moneyUtils.formatMoney(growthAmount) }}</span>
        </div>
      </div>
      <div class="overview-tip">点击查看明细</div>
    </div>
    
    <!-- 港币钱包模块 -->
    <div class="hkd-wallet-card">
      <div class="hkd-wallet-title">港币钱包</div>
      <div class="hkd-wallet-content">
        <div class="hkd-wallet-row">
          <span class="hkd-wallet-label">当前汇率</span>
          <div class="hkd-wallet-value">
            <span>{{ moneyUtils.formatMoney(hkdWallet.rate, 3) }}</span>
            <van-button size="mini" class="edit-btn" @click="showEditRate = true">修改</van-button>
          </div>
        </div>
        <div class="hkd-wallet-row">
          <span class="hkd-wallet-label">港币钱包</span>
          <div class="hkd-wallet-value">
            <span>HK$ {{ moneyUtils.formatMoney(hkdWallet.amount) }}</span>
            <van-button size="mini" class="edit-btn" @click="showEditAmount = true">修改</van-button>
          </div>
        </div>
        <div class="hkd-wallet-row">
          <span class="hkd-wallet-label">折合人民币</span>
          <span class="hkd-wallet-value">￥{{ moneyUtils.formatMoney(hkdWallet.cny) }}</span>
        </div>
      </div>
    </div>
    
    <!-- 编辑汇率弹窗 -->
    <van-dialog v-model:show="showEditRate" title="修改港币汇率" show-cancel-button @confirm="updateRate">
      <van-field v-model="editRateValue" label="汇率" placeholder="请输入汇率" type="number" />
    </van-dialog>
    
    <!-- 编辑港币金额弹窗 -->
    <van-dialog v-model:show="showEditAmount" title="修改港币金额" show-cancel-button @confirm="updateAmount">
      <van-field v-model="editAmountValue" label="金额" placeholder="请输入港币金额" type="number" />
    </van-dialog>
    
    <!-- 编辑昨日总额弹窗 -->
    <van-dialog v-model:show="showEditYesterday" title="修改昨日总额" show-cancel-button @confirm="handleUpdateYesterdayAmount">
      <van-field v-model="editYesterdayValue" label="金额" placeholder="请输入昨日总额" type="number" />
    </van-dialog>
    
    <!-- 气泡明细 -->
    <van-popup v-model:show="showIncomeExpenseDetail" position="bottom" round :style="{ padding: '24px 0', borderRadius: '16px 16px 0 0' }">
      <div class="popup-detail">
        <div class="popup-title">总额明细</div>
        <div class="amount-overview">
          <div class="amount-overview-item">
            <div class="amount-label">当前总额</div>
            <div class="amount-value income">￥{{ moneyUtils.formatMoney(overview.amount) }}</div>
          </div>
          <div class="amount-overview-item">
            <div class="amount-label">账户总额</div>
            <div class="amount-value income">￥{{ moneyUtils.formatMoney(overview.accountAmount) }}</div>
          </div>
          <div class="amount-overview-item">
            <div class="amount-label">钱包总额</div>
            <div class="amount-value income">￥{{ moneyUtils.formatMoney(overview.hkdCny) }}</div>
          </div>
        </div>
      </div>
    </van-popup>
    <!-- 账户列表 -->
    <div class="account-list-title">账户列表</div>
    <div class="account-list">
      <div
        class="account-card"
        v-for="account in accounts"
        :key="account.id"
        @click="goAccount(account.id)"
      >
        <div class="account-name">
          {{ account.name }}
          <van-button size="mini" class="delete-btn" @click.stop="showDeleteAccountConfirm(account)">删除</van-button>
        </div>
        <div class="account-amounts">
          <span class="total">总金额：<b>￥{{ account.total }}</b></span>
          <span class="ali">支付宝：￥{{ account.ali }}</span>
          <span class="wx">微信：￥{{ account.wx }}</span>
          <span class="bank">银行卡：￥{{ account.bank || 0 }}</span>
          <span class="credit-card">信用卡：￥{{ account.credit_card || 0 }}</span>
        </div>
      </div>
    </div>
    <!-- 扁平添加账户按钮 -->
    <van-button type="primary" class="flat-add-account-btn" @click="showAddAccount = true">
      ＋ 添加账户
    </van-button>
    <!-- 添加账户模态 -->
    <van-dialog v-model:show="showAddAccount" title="添加账户" show-cancel-button @confirm="onAddAccountConfirm">
      <van-field v-model="newAccountName" label="账户名称" placeholder="请输入账户名称" maxlength="10" />
    </van-dialog>
    
    <!-- 删除账户确认弹窗 -->
    <van-dialog
      v-model:show="showDeleteConfirm"
      title="删除确认"
      show-cancel-button
      @confirm="confirmDeleteAccount"
    >
      <div style="padding: 20px 16px;">
        确定要删除账户"{{ accountToDelete.name }}"吗？账户下的所有交易记录将被标记为已删除。
      </div>
    </van-dialog>
    
    <!-- 添加记录悬浮按钮 -->
    <van-button type="primary" class="add-btn" @click="goAddRecord">
      <span class="add-btn-icon">＋</span> 添加记录
    </van-button>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { Popup, List, Cell, Button, Dialog, Field, showSuccessToast, showFailToast, Popover, Icon } from 'vant'
import { accountApi, overviewApi, userApi, updateHkdAmount, updateHkdRate, updateYesterdayAmount } from '@/api'
import config from '@/config'
import dateUtils from '@/utils/date'
import numberUtils from '@/utils/number'
import moneyUtils from '@/utils/money'

const router = useRouter()
const showIncomeExpenseDetail = ref(false)
const overview = ref({
  income: 0,
  expense: 0,
  wxIncome: 0,
  aliIncome: 0,
  bankIncome: 0,
  wxExpense: 0,
  aliExpense: 0,
  bankExpense: 0,
  amount: 0,
  accountAmount: 0,
  hkdCny: 0,
  yesterdayAmount: 0,
  yesterdayAccountAmount: 0,
  yesterdayHkdCny: 0
})
const accounts = ref([])
const showAddAccount = ref(false)
const newAccountName = ref('')

const hkdWallet = ref({
  amount: 0,
  rate: 0.935,
  cny: 0
})
const showEditRate = ref(false)
const showEditAmount = ref(false)
const editRateValue = ref('')
const editAmountValue = ref('')
const showEditYesterday = ref(false)
const editYesterdayValue = ref('')

const showDeleteConfirm = ref(false)
const accountToDelete = ref({ id: null, name: '' })
const showUserMenu = ref(false)

// 计算增长金额（账户总额 - 昨日总额）
const growthAmount = computed(() => {
  const currentAmount = overview.value.amount || 0;
  const yesterdayAmount = overview.value.yesterdayAmount || 0;
  const growth = moneyUtils.subtract(currentAmount, yesterdayAmount);
  return growth;
});

async function fetchOverview() {
  try {
    const data = await overviewApi.getOverview()
    overview.value = data
    
    // 从overview中获取港币钱包信息
    if (data.hkdWallet) {
      hkdWallet.value = data.hkdWallet
    }
  } catch (error) {
    console.error('获取总览数据失败:', error)
    showFailToast('获取总览数据失败')
  }
}

async function fetchAccounts() {
  try {
    const data = await accountApi.getAccounts()
    accounts.value = data
    console.log(`使用环境: ${config.env}, 基础URL: ${config.baseUrl}`)
  } catch (error) {
    console.error('获取账户列表失败:', error)
    showFailToast('获取账户列表失败')
  }
}

function goAccount(id) {
  router.push(`/account/${id}`)
}
function goAddRecord() {
  router.push('/record/edit')
}
async function onAddAccountConfirm() {
  if (!newAccountName.value.trim()) {
    showFailToast('账户名称不能为空')
    return false
  }
  
  try {
    await accountApi.createAccount({
      name: newAccountName.value.trim(),
      ali: 0,
      wx: 0,
      bank: 0,
      total: 0,
    })
    showSuccessToast('添加成功')
    showAddAccount.value = false
    newAccountName.value = ''
    fetchAccounts()
  } catch (error) {
    console.error('添加账户失败:', error)
    showFailToast('添加账户失败')
  }
}

async function updateRate() {
  if (!editRateValue.value || isNaN(parseFloat(editRateValue.value)) || parseFloat(editRateValue.value) <= 0) {
    showFailToast('请输入有效的汇率')
    return false
  }
  
  try {
    const response = await updateHkdRate(parseFloat(editRateValue.value))
    if (response && response.hkd_wallet) {
      hkdWallet.value = response.hkd_wallet
      console.log('更新后的港币钱包数据:', hkdWallet.value)
    }
    showSuccessToast('汇率更新成功')
    editRateValue.value = ''
    // 更新账户总览
    fetchOverview()
  } catch (error) {
    console.error('更新汇率失败:', error)
    showFailToast('更新汇率失败')
  }
}

async function updateAmount() {
  if (!editAmountValue.value || isNaN(parseFloat(editAmountValue.value))) {
    showFailToast('请输入有效的金额')
    return false
  }
  
  try {
    const response = await updateHkdAmount(parseFloat(editAmountValue.value))
    if (response && response.hkd_wallet) {
      hkdWallet.value = response.hkd_wallet
      console.log('更新后的港币钱包数据:', hkdWallet.value)
    }
    showSuccessToast('港币金额更新成功')
    editAmountValue.value = ''
    // 更新账户总览
    fetchOverview()
  } catch (error) {
    console.error('更新港币金额失败:', error)
    showFailToast('更新港币金额失败')
  }
}

async function handleUpdateYesterdayAmount() {
  if (!editYesterdayValue.value || isNaN(parseFloat(editYesterdayValue.value))) {
    showFailToast('请输入有效的金额')
    return false
  }
  
  try {
    const { yesterday_amount } = await updateYesterdayAmount(parseFloat(editYesterdayValue.value))
    overview.value.yesterdayAmount = yesterday_amount
    showSuccessToast('昨日总额更新成功')
    editYesterdayValue.value = ''
    // 更新总览数据
    fetchOverview()
    // 删除对fetchUserInfo的调用
  } catch (error) {
    console.error('更新昨日总额失败:', error)
    showFailToast('更新昨日总额失败')
  }
}

function showDeleteAccountConfirm(account) {
  accountToDelete.value = account
  showDeleteConfirm.value = true
}

async function confirmDeleteAccount() {
  if (!accountToDelete.value.id) return
  
  try {
    await accountApi.deleteAccount(accountToDelete.value.id)
    showSuccessToast('账户删除成功')
    // 重新获取账户列表和总览数据
    fetchAccounts()
    fetchOverview()
  } catch (error) {
    console.error('删除账户失败:', error)
    showFailToast('删除账户失败')
  }
}

function goToResetPassword() {
  router.push('/reset-password')
}

function logout() {
  // 清除本地存储的token和用户信息
  localStorage.removeItem('token')
  localStorage.removeItem('user')
  // 跳转到登录页
  router.push('/login')
}

onMounted(() => {
  fetchAccounts()
  fetchOverview()
})
</script>

<style scoped>
.home-container {
  min-height: 100vh;
  background: #f6f7fb;
  padding: 16px 6px 80px 6px;
}
.overview-card {
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.04);
  padding: 16px 16px 10px 16px;
  cursor: pointer;
  transition: box-shadow 0.2s;
}
.overview-card:active {
  box-shadow: 0 4px 16px 0 rgba(0,0,0,0.08);
}
.overview-title {
  font-size: 16px;
  color: #333;
  font-weight: 600;
  margin-bottom: 8px;
}
.overview-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
  flex-wrap: wrap;
  gap: 6px;
}
.overview-item {
  flex: 1;
  text-align: left;
  padding: 0 4px;
  position: relative;
  min-width: 30%;
  margin-bottom: 6px;
}
.overview-item span {
  display: block;
  white-space: nowrap;
}
.overview-item .label {
  font-size: 12px;
  color: #666;
  margin-bottom: 1px;
  display: flex;
  align-items: center;
}
.overview-item.income .amount {
  color: #27c19e;
  font-size: 14px;
  font-weight: bold;
  white-space: normal;
}
.overview-item.expense .amount {
  color: #ff5b5b;
  font-size: 14px;
  font-weight: bold;
  white-space: normal;
}
.overview-tip {
  font-size: 12px;
  color: #aaa;
  text-align: right;
  margin-top: 2px;
}
.popup-detail {
  width: 90vw;
  max-width: 400px;
  margin: 0 auto;
}
.popup-title {
  font-size: 15px;
  color: #333;
  font-weight: 600;
  margin-bottom: 8px;
}
.popup-row {
  display: flex;
  justify-content: space-between;
  padding: 6px 0;
  font-size: 15px;
}
.popup-label {
  font-weight: 500;
}
.popup-label.wechat {
  color: #07c160;
}
.popup-label.alipay {
  color: #1677ff;
}
.popup-label.bank {
  color: #ff9500;
}
.popup-value {
  font-weight: bold;
}
.account-list-title {
  font-size: 15px;
  color: #666;
  margin: 18px 0 6px 18px;
  font-weight: 500;
}
.account-card {
  background: #fff;
  border-radius: 14px;
  box-shadow: 0 1px 6px 0 rgba(0,0,0,0.03);
  margin-bottom: 14px;
  padding: 14px 16px 10px 16px;
  transition: box-shadow 0.2s;
  cursor: pointer;
}
.account-card:active {
  box-shadow: 0 4px 16px 0 rgba(0,0,0,0.08);
}
.account-name {
  font-size: 16px;
  font-weight: 600;
  color: #222;
  margin-bottom: 6px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.account-name .delete-btn {
  background: #fff0f0;
  color: #ff5b5b;
  border: none;
  border-radius: 12px;
  font-size: 13px;
  padding: 2px 12px;
}

.account-amounts {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  font-size: 13px;
  color: #888;
}
.account-amounts > span {
  white-space: normal;
  display: inline-block;
  font-size: 12px;
}
.account-amounts .total {
  color: #27c19e;
}
.account-amounts .ali {
  color: #1677ff;
}
.account-amounts .wx {
  color: #07c160;
}
.account-amounts .bank {
  color: #ff9500;
}
.account-amounts .credit-card {
  color: #9c27b0;
}
.add-btn {
  position: fixed;
  left: 50%;
  bottom: 32px;
  transform: translateX(-50%);
  width: 90vw;
  max-width: 400px;
  height: 48px;
  border-radius: 24px;
  font-size: 18px;
  font-weight: 600;
  box-shadow: 0 4px 16px 0 rgba(39,193,158,0.12);
  display: flex;
  align-items: center;
  justify-content: center;
}
.add-btn-icon {
  font-size: 22px;
  margin-right: 6px;
  font-weight: bold;
}
.flat-add-account-btn {
  display: block;
  margin: 0 auto 18px auto;
  width: 60vw;
  max-width: 320px;
  height: 40px;
  border-radius: 20px;
  font-size: 16px;
  font-weight: 500;
  background: #27c19e;
  color: #fff;
  box-shadow: 0 2px 8px 0 rgba(39,193,158,0.08);
  border: none;
}
.flat-add-account-btn:active {
  background: #1fa885;
}

.hkd-wallet-card {
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.04);
  padding: 20px 18px;
  margin-top: 16px;
}

.hkd-wallet-title {
  font-size: 16px;
  color: #333;
  font-weight: 600;
  margin-bottom: 12px;
}

.hkd-wallet-content {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.hkd-wallet-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.hkd-wallet-label {
  font-size: 14px;
  color: #666;
}

.hkd-wallet-value {
  font-size: 13px;
  font-weight: 500;
  color: #333;
  display: flex;
  align-items: center;
  gap: 8px;
  white-space: normal;
}

.edit-btn {
  font-size: 12px;
  padding: 0 8px;
  height: 24px;
  line-height: 24px;
  background: #f5f5f5;
  color: #666;
  border: none;
}

.small-edit-btn {
  font-size: 10px;
  padding: 0 4px;
  height: 20px;
  line-height: 20px;
  background: #f5f5f5;
  color: #666;
  border: none;
}

.divider {
  height: 1px;
  background: #eee;
  margin: 16px 0;
}

.amount-overview {
  display: flex;
  flex-direction: column;
  gap: 12px;
  margin: 10px 0;
}

.amount-overview-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.amount-label {
  font-size: 15px;
  color: #444;
}

.amount-value {
  font-size: 13px;
  font-weight: 600;
  white-space: normal;
}

.amount-value.income {
  color: #27c19e;
}

.amount-value.expense {
  color: #ff5b5b;
}

.amount-with-button {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
}

.yesterday-item .amount {
  display: inline;
}

.user-settings {
  position: absolute;
  top: 16px;
  right: 16px;
  z-index: 10;
}

.user-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background-color: #27c19e;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.menu-item {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  cursor: pointer;
}

.menu-item span {
  margin-left: 8px;
}
</style> 